/*******************************************************************************
 * Copyright (c) 2012 Alexandr Tsvetkov.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Alexandr Tsvetkov - initial API and implementation
 * 
 * Project:
 *     TAO Library
 * 
 * File name:
 *     ProgressManager.java
 *     
 * License agreement:
 *
 * 1. This code is published AS IS. Author is not responsible for any damage that can be
 *    caused by any application that uses this code.
 * 2. Author does not give a garantee, that this code is error free.
 * 3. This code can be used in NON-COMMERCIAL applications AS IS without any special
 *    permission from author.
 * 4. This code can be modified without any special permission from author IF AND ONLY IF
 *    this license agreement will remain unchanged.
 * 5. SPECIAL PERMISSION for this code usage in COMMERCIAL application SHOULD be obtained
 *    from author.
 ******************************************************************************/
package ua.at.tsvetkov.ui;

import java.text.DecimalFormat;

import android.app.Activity;
import android.app.ProgressDialog;

/**
 * @author A.Tsvetkov
 */
public class ProgressManager {

	private Activity			context;
	private ProgressDialog	progress;
	private int					parts;
	private float				size;
	private float				previosSize;
	private int					delta;
	private long				timeBegin;
	private int					part;

	/**
	 * @param context текущий контекст
	 * @param dialogId номер диалога
	 * @param title титл
	 * @param max максимальное число
	 * @param parts загрузок
	 */
	public ProgressManager(Activity context, final ProgressDialog progress, final String title, final int max, final int parts) {
		this.progress = progress;
		this.context = context;
		this.parts = parts;
		this.delta = max / parts;
		this.timeBegin = System.currentTimeMillis();
		this.part = 0;
		this.size = 0;
		this.previosSize = 0;
		context.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				progress.setTitle(title);
				progress.setMax(max);
			}
		});
	}

	public void init(final int max, final int parts) {
		this.parts = parts;
		this.delta = max / parts;
		this.timeBegin = System.currentTimeMillis();
		this.part = 0;
		this.size = 0;
		this.previosSize = 0;
		context.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				progress.setMax(max);
			}
		});
	}

	/**
	 * Удаляет диалог
	 */
	public void remove() {
		context.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				progress.dismiss();
			}
		});
	}

	/**
	 * Удаляет диалог
	 */
	public void setMax(final int max) {
		context.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				progress.setMax(max);
			}
		});
	}

	/**
	 * Удаляет диалог
	 */
	public void setProgress(final int value) {
		context.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				progress.setProgress(value);
			}
		});
	}

	/**
	 * Увеличивается на указанное число.
	 * 
	 * @param value
	 */
	public void increment(final float value) {
		size = size + value;
		if (size - previosSize > delta) {
			previosSize = size;
			final String st = makeProgressMessage();
			context.runOnUiThread(new Runnable() {

				@Override
				public void run() {
					progress.setMessage(st);
					progress.setProgress((int) size);
				}
			});
		}
	}

	/**
	 * Увеличивается на указанное число.
	 * 
	 * @param value
	 */
	public void setIntermediate(final boolean intermediate) {
		context.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				progress.setIndeterminate(intermediate);
			}
		});
	}

	/**
	 * Устанавливается новый заголовок и сообщение.
	 * 
	 * @param title
	 * @param message
	 */
	public void setTitleAndMessage(final CharSequence title, final CharSequence message) {
		context.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				progress.setTitle(title);
				progress.setMessage(message);
			}
		});
	}

	/**
	 * Устанавливается новый заголовок.
	 * 
	 * @param title
	 */
	public void setTitle(final CharSequence title) {
		context.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				progress.setTitle(title);
			}
		});
	}

	/**
	 * Устанавливается новое сообщение.
	 * 
	 * @param message
	 */
	public void setMessage(final CharSequence message) {
		context.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				progress.setMessage(message);
			}
		});
	}

	/**
	 * Возвращает строку описывающую сколько осталось времени на загрузку.
	 * 
	 * @return
	 */
	private String makeProgressMessage() {
		part++;
		long cur = System.currentTimeMillis();
		long time = (((cur - timeBegin) / part) * (parts - part)) / 1000;
		long chas = time / 360;
		long min = time % 360 / 60;
		long sec = time - (chas * 360 + min * 60);
		if (sec < 0)
			sec = 0;
		DecimalFormat formatter = new DecimalFormat("00");
		String st;
		if (chas > 0) {
			st = "Ожидаемое время загрузки\n" + formatter.format(chas) + " ч " + formatter.format(min) + " мин " + formatter.format(sec) + " с";
		} else {
			st = "Ожидаемое время загрузки\n" + formatter.format(min) + " мин " + formatter.format(sec) + " с";
		}
		return st;
	}

}
